package com.zhuhjay.utils.result;

import cn.hutool.core.bean.BeanUtil;
import com.zhuhjay.enums.HttpCode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 当需要返回的数据不是单一的数据时，可以使用该类来封装数据( @Jackson 注解不生效 )
 * @author ZhuHJay
 * @date 2023/1/11 13:32
 */
public class ResultMap extends HashMap<String, Object> implements Result {
    /** 定义集合中`key`的标签 **/
    private static final String STATUS_TAG = "code";
    private static final String MESSAGE_TAG = "message";
    private static final String DATA_TAG = "data";
    /** 用来存放数据的集合 **/
    private final Map<String, Object> dataMap = new HashMap<>();

    private ResultMap(int code, String message){
        super.put(STATUS_TAG, code);
        super.put(MESSAGE_TAG, message);
        super.put(DATA_TAG, dataMap);
    }

    private static ResultMap createResult(HttpCode code, String message) {
        return new ResultMap(code.getCode(), message);
    }

    public static ResultMap ok(HttpCode code, String message) {
        return createResult(code, message);
    }

    public static ResultMap ok(HttpCode code) {
        return createResult(code, code.getDesc());
    }

    public static ResultMap ok(String message){
        return createResult(HttpCode.SUCCESS, message);
    }

    public static ResultMap ok(){
        return ResultMap.ok(HttpCode.SUCCESS.getDesc());
    }

    public static ResultMap fail(HttpCode code, String message) {
        return createResult(code, message);
    }

    public static ResultMap fail(HttpCode code) {
        return createResult(code, code.getDesc());
    }

    public static ResultMap fail(String message){
        return createResult(HttpCode.USER_ERROR, message);
    }

    public static ResultMap fail(){
        return fail(HttpCode.USER_ERROR.getDesc());
    }

    public ResultMap data(String key, Object value){
        dataMap.put(key, value);
        return this;
    }

    /** 拷贝Bean到data数据域中，可选拷贝哪些属性值，null或空表示拷贝所有值 **/
    public ResultMap beanToData(Object o, String ...properties) {
        if (o instanceof List) {
            dataMap.put("list", o);
        } else {
            dataMap.putAll(BeanUtil.beanToMap(o, properties));
        }
        return this;
    }

    @Override
    public int getCode() {
        return (int) super.get(STATUS_TAG);
    }

    @Override
    public String getMessage() {
        return (String) super.get(MESSAGE_TAG);
    }

    @Override
    public Object getData() {
        return super.get(DATA_TAG);
    }
}
